﻿using System;
using System.Collections.Generic;
using KC.Common;
using KC.Service.Core.Enums.WorkFlow;
using KC.Framework.Base;
using KC.Framework.Tenant;
using KC.DTO.Account;
using KC.DTO.Core;
using KC.Service.Core.DTO.WorkFlow;

namespace KC.Service.Core.WebApiService.Business
{
    public class WorkFlowApiService : IdSrvOAuth2ClientRequestBase, IWorkFlowApiService
    {
        private const string ServiceName = "KC.Service.WorkFlow.WebApiService.Business.WorkFlowApiService";
        public WorkFlowApiService(
            Tenant tenant, 
            System.Net.Http.IHttpClientFactory httpClient,
            Microsoft.Extensions.Logging.ILogger<WorkFlowApiService> logger)
            : base(TenantConstant.DbaTenantApiAccessInfo, httpClient, logger)
        {
        }

        /// <summary>
        /// 获取流程列表
        /// </summary>
        /// <param name="operatorid"></param>
        /// <param name="applycode"></param>
        /// <returns></returns>
        public ServiceResult<PaginatedBaseDTO<WorkFlowGroupDto>> FindWorkFlowGroup(int pageIndex, int pageSize, string applycode, string operatorid = null)
        {
            ServiceResult<PaginatedBaseDTO<WorkFlowGroupDto>> result = null;
            WebSendGet<ServiceResult<PaginatedBaseDTO<WorkFlowGroupDto>>>(
                ServiceName + ".FindWorkFlowGroup",
                FlowApiServerUrl + "WorkFlowApi/FindWorkFlowGroup?pageIndex=" + pageIndex + "&pageSize=" + pageSize + "&applycode=" + applycode + "&operatorid=" + operatorid,
                ApplicationConstant.FlowScope,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<PaginatedBaseDTO<WorkFlowGroupDto>>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }

        public ServiceResult<PaginatedBaseDTO<WorkFlowTaskDto>> GetAllWorkFlowTask(int pageIndex, int pageSize, string userId, Guid appId)
        {
            ServiceResult<PaginatedBaseDTO<WorkFlowTaskDto>> result = null;
            WebSendGet<ServiceResult<PaginatedBaseDTO<WorkFlowTaskDto>>>(
                ServiceName + ".GetAllWorkFlowTask",
                FlowApiServerUrl + "WorkFlowApi/GetAllWorkFlowTask?pageIndex=" + pageIndex + "&pageSize=" + pageSize + "&userId=" + userId + "&appId=" + appId,
                ApplicationConstant.FlowScope,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<PaginatedBaseDTO<WorkFlowTaskDto>>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }

        public ServiceResult<int> GetWorkFlowTaskCount(string userId, Guid appId)
        {
            string application = appId.ToString();
            ServiceResult<int> result = null;
            WebSendGet<ServiceResult<int>>(
                ServiceName + ".GetWorkFlowTaskCount",
                FlowApiServerUrl + "WorkFlowApi/GetWorkFlowTaskCount?userId=" + userId + "&appId=" + application,
                ApplicationConstant.FlowScope,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<int>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }

        public ServiceResult<PaginatedBaseDTO<WorkFlowTaskLogDto>> FindWorkFlowTaskLog(int pageIndex, int pageSize, string orderid)
        {
            ServiceResult<PaginatedBaseDTO<WorkFlowTaskLogDto>> result = null;
            WebSendGet<ServiceResult<PaginatedBaseDTO<WorkFlowTaskLogDto>>>(
                ServiceName + ".FindWorkFlowTaskLog",
                FlowApiServerUrl + "WorkFlowApi/FindWorkFlowTaskLog?pageIndex=" + pageIndex + "&pageSize=" + pageSize + "&orderid=" + orderid,
                ApplicationConstant.FlowScope,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<PaginatedBaseDTO<WorkFlowTaskLogDto>>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }



        public ServiceResult<bool> ApplyFlow(string applycode, WorkFlowTaskDto model, string username)
        {
            var postData = SerializeHelper.ToJson(model);
            ServiceResult<bool> result = null;
            WebSendPost<ServiceResult<bool>>(
                ServiceName + ".ApplyFlow",
                FlowApiServerUrl + "WorkFlowApi/ApplyFlow?applycode=" + applycode + "&username=" + username,
                postData,
                ApplicationConstant.FlowScope,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<bool>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }


        public ServiceResult<ProcessingState> GetProcessingState(string orderid)
        {
            ServiceResult<ProcessingState> result = null;
            WebSendGet<ServiceResult<ProcessingState>>(
                ServiceName + ".GetProcessingState",
                FlowApiServerUrl + "WorkFlowApi/GetProcessingState?orderid=" + orderid,
                ApplicationConstant.FlowScope,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<ProcessingState>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }


        public ServiceResult<bool> UpdateWorkFlowStatus(string url, string applyCode, string id, Framework.Base.WorkFlowStatus status)
        {
            ServiceResult<bool> result = null;
            WebSendGet<ServiceResult<bool>>(
                ServiceName + ".GetProcessingState",
                MarketApiServerUrl + url + "?applyCode=" + applyCode + "&creditId=" + id + "&status=" + status,
                ApplicationConstant.FlowScope,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<bool>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }


        /// <summary>
        /// 审批中心更新业务流程
        /// </summary>
        /// <param name="url">回调URL</param>
        /// <param name="busiBase">更新的数据对象</param>
        /// <returns></returns>
        public ServiceResult<string> UpdateBusinessFlowStat(string url, FlowBusiBase busiBase)
        {
            var postData = SerializeHelper.ToJson(busiBase);
            ServiceResult<string> result = null;
            WebSendPost<ServiceResult<string>>(
                ServiceName + ".UpdateBusinessFlowStat",
                FlowApiServerUrl + url,
                ApplicationConstant.FlowScope,
                postData,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<string>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);

            return result;
        }

        /// <summary>
        /// 获取待审批列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="appid"></param>
        /// <param name="flowtype"></param>
        /// <param name="curuserid"></param>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        public ServiceResult<PaginatedBaseDTO<ApproveDataDto>> GetPagenatedFlowRecordsByFilter(int pageIndex, int pageSize, string appid, int? flowtype,
            Guid curuserid, string code, string name, string sort)
        {
            ServiceResult<PaginatedBaseDTO<ApproveDataDto>> result = null;
            WebSendGet<ServiceResult<PaginatedBaseDTO<ApproveDataDto>>>(
                ServiceName + ".GetPagenatedFlowRecordsByFilter",
                FlowApiServerUrl + "WorkFlowApi/GetPagenatedFlowRecordsByFilter?pageIndex=" + pageIndex + 
                    "&pageSize=" + pageSize + "&appid=" + appid + "&flowtype=" + flowtype + 
                    "&curuserid=" + curuserid + "&code=" + code + "&name=" + name + "&sort=" + sort,
                ApplicationConstant.FlowScope,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<PaginatedBaseDTO<ApproveDataDto>>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }

        #region ERP的接口


        /// <summary>
        /// 发起审批
        /// </summary>
        /// <param name="origDto"></param>
        /// <returns></returns>
        public ServiceResult<int> StartFlow(FlowOrigRecordsDto origDto)
        {
            var postData = SerializeHelper.ToJson(origDto);
            ServiceResult<int> result = null;
            WebSendPost<ServiceResult<int>>(
                ServiceName + ".StartFlow",
                FlowApiServerUrl + "WorkFlowApi/StartFlow",
                ApplicationConstant.FlowScope,
                postData,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<int>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }

        //public ServiceResult<Guid> JudeFlow(JudeFlowEntityDTO origDto)
        //{
        //    var postData = SerializeHelper.ToJson(origDto);
        //    ServiceResult<Guid> result = null;
        //    WebSendPost<ServiceResult<Guid>>(
        //        ServiceName + ".JudeFlow",
        //        FlowApiServerUrl + "WorkFlowApi/JudeFlow",
        //        postData,
        //        callback =>
        //        {
        //            result = callback;
        //        },
        //        (httpStatusCode, errorMessage) =>
        //        {
        //            result = new ServiceResult<Guid>(ServiceResultType.Error, httpStatusCode, errorMessage);
        //        },
        //        true);
        //    return result;
        //}

        public ServiceResult<FlowOrigRecordsDto> CancelFlow(int flowid, Guid userid, string usercode, string username)
        {
            ServiceResult<FlowOrigRecordsDto> result = null;
            WebSendGet<ServiceResult<FlowOrigRecordsDto>>(
                ServiceName + ".CancelFlow",
                FlowApiServerUrl + "WorkFlowApi/CancelFlow?flowid=" + flowid + "&userid=" + userid + "&usercode=" + usercode + "&username=" + username,
                ApplicationConstant.FlowScope,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<FlowOrigRecordsDto>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }

        public ServiceResult<FlowOrigRecordsDto> ResetFlow(int flowid, Guid userid, string usercode, string username)
        {
            ServiceResult<FlowOrigRecordsDto> result = null;
            WebSendGet<ServiceResult<FlowOrigRecordsDto>>(
                ServiceName + ".ResetFlow",
                FlowApiServerUrl + "WorkFlowApi/ResetFlow?flowid=" + flowid + "&userid=" + userid + "&usercode=" + usercode + "&username=" + username,
                ApplicationConstant.FlowScope,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<FlowOrigRecordsDto>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }

        /// <summary>
        /// 流程数据回滚
        /// </summary>
        /// <param name="busiBase"></param>
        /// <returns></returns>
        public ServiceResult<string> RollBackFlow(FlowBusiBase busiBase)
        {
            ServiceResult<string> result = null;
            var postData = SerializeHelper.ToJson(busiBase);
            WebSendPost<ServiceResult<string>>(
                ServiceName + ".ResetFlow",
                FlowApiServerUrl + "WorkFlowApi/RollBackFlow",
                postData,
                ApplicationConstant.FlowScope,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<string>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }

        public ServiceResult<List<string[]>> GetFlowDetailByWorkId(string workid)
        {
            ServiceResult<List<string[]>> result = null;
            WebSendGet<ServiceResult<List<string[]>>>(
                ServiceName + ".GetFlowDetailByWorkId",
                FlowApiServerUrl + "WorkFlowApi/GetFlowDetailByWorkId?workid=" + workid,
                ApplicationConstant.FlowScope,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<List<string[]>>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }

        public ServiceResult<List<Dictionary<string, List<string[]>>>> ErpViewFlowDetail(string workid, ErpFlowConfigs flowconfigs)
        {
            ServiceResult<List<Dictionary<string, List<string[]>>>> result = null;
            var postData = SerializeHelper.ToJson(flowconfigs);
            WebSendPost<ServiceResult<List<Dictionary<string, List<string[]>>>>>(
                ServiceName + ".ErpViewFlowDetail",
                FlowApiServerUrl + "WorkFlowApi/ErpGetFlowDetail?workid=" + workid,
                ApplicationConstant.FlowScope,
                postData,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<List<Dictionary<string, List<string[]>>>>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }

        /// <summary>
        /// 获取审批步骤对应的审批人员
        /// </summary>
        /// <param name="curStep"></param>
        /// <returns></returns>
        public ServiceResult<List<UserDTO>> GetAllAppUsersByStep(FlowListsDto curStep)
        {
            var postData = SerializeHelper.ToJson(curStep);
            ServiceResult<List<UserDTO>> result = null;
            WebSendPost<ServiceResult<List<UserDTO>>>(
                ServiceName + ".GetAllAppUsersByStep",
                FlowApiServerUrl + "WorkFlowApi/GetAllAppUsersByStep",
                ApplicationConstant.FlowScope,
                postData,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<List<UserDTO>>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }

        /// <summary>
        /// 通过业务配置获取默认审批流程
        /// </summary>
        /// <param name="flowConfig"></param>
        /// <returns></returns>
        public ServiceResult<FlowBusiDefaultDto> GetDefautFlowByType(ErpBusiFlowConfig flowConfig)
        {
            ServiceResult<FlowBusiDefaultDto> result = null;
            WebSendGet<ServiceResult<FlowBusiDefaultDto>>(
                ServiceName + ".GetDefautFlowByType",
                FlowApiServerUrl + "WorkFlowApi/GetDefaultFlowByType?busitype=" + flowConfig,
                ApplicationConstant.FlowScope,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<FlowBusiDefaultDto>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }

        /// <summary>
        /// 获取流程审批步骤的所有信息
        /// </summary>
        /// <param name="flowid"></param>
        /// <param name="step"></param>
        /// <returns></returns>
        public ServiceResult<FlowListsDto> GetFlowStepByFlowIdAndStepId(int flowid, int step)
        {
            ServiceResult<FlowListsDto> result = null;
            WebSendGet<ServiceResult<FlowListsDto>>(
                ServiceName + ".GetFlowStepByFlowId",
                FlowApiServerUrl + "WorkFlowApi/GetFlowStepByFlowId?flowid=" + flowid + "&step=" + step,
                ApplicationConstant.FlowScope,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<FlowListsDto>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }
        /// <summary>
        /// 获取发起审批的记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ServiceResult<FlowOrigRecordsDto> GetOrigRecordById(int id)
        {
            ServiceResult<FlowOrigRecordsDto> result = null;
            WebSendGet<ServiceResult<FlowOrigRecordsDto>>(
                ServiceName + ".GetOrigRecordById",
                FlowApiServerUrl + "WorkFlowApi/GetOrigRecordById?id=" + id,
                ApplicationConstant.FlowScope,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<FlowOrigRecordsDto>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }

        /// <summary>
        /// 获取审批步骤审批信息
        /// </summary>
        /// <param name="workid"></param>
        /// <param name="flowid"></param>
        /// <param name="type"></param>
        /// <param name="step"></param>
        /// <returns></returns>
        public ServiceResult<FlowListsDto> GetFlowStepByWorkIdAndFlowid(string workid, int type, int? step = null)
        {
            ServiceResult<FlowListsDto> result = null;
            WebSendGet<ServiceResult<FlowListsDto>>(
                ServiceName + ".GetFlowStepByWorkIdAndFlowid",
                FlowApiServerUrl + "WorkFlowApi/GetFlowStepByWorkIdAndFlowid?workid=" + workid + "&type=" + type + "&step=" + step,
                ApplicationConstant.FlowScope,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<FlowListsDto>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }

        /// <summary>
        /// 获取最近一次审批信息
        /// </summary>
        /// <param name="workid"></param>
        /// <param name="flowid"></param>
        /// <returns></returns>
        public ServiceResult<FlowResultsDto> GetRecentFlowResultByWorkIdAndFlowId(string workid)
        {
            ServiceResult<FlowResultsDto> result = null;
            WebSendGet<ServiceResult<FlowResultsDto>>(
                ServiceName + ".GetRecentFlowResultByWorkIdAndFlowId",
                FlowApiServerUrl + "WorkFlowApi/GetRecentFlowResult?workid=" + workid,
                ApplicationConstant.FlowScope,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<FlowResultsDto>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);
            return result;
        }

        #endregion

        /// <summary>
        /// 测试接口是否存在
        /// </summary>
        /// <returns></returns>
        public ServiceResult<bool> ExistTenantService()
        {
            ServiceResult<bool> result = null;
            WebSendGet<ServiceResult<bool>>(
                ServiceName + ".ExistTenantService",
                FlowApiServerUrl + "WorkFlowApi/ExistTenantService",
                ApplicationConstant.FlowScope,
                callback =>
                {
                    result = callback;
                },
                (httpStatusCode, errorMessage) =>
                {
                    result = new ServiceResult<bool>(ServiceResultType.Error, httpStatusCode, errorMessage);
                },
                true);

            return result;
        }
    }
}
